<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="card-header">
          <span>扫码打包</span>
          <div class="mode-switch">

            <el-button-group>
              <el-button :type="packMode === 'normal' ? 'primary' : 'default'" @click="switchMode('normal')">
                普通打包
              </el-button>

              <el-button :type="packMode === 'piece' ? 'primary' : 'default'" @click="switchMode('piece')">
                按件打包
              </el-button>
            </el-button-group>
          </div>
        </div>
      </div>

      <el-form ref="packForm" :model="packForm" :rules="rules" label-width="120px" class="pack-form">
        <el-form-item label="小包数量" prop="number" v-if="packMode === 'normal'">
          <!-- 普通模式：输入框 -->
          <el-input
            v-model="packForm.number"
            placeholder="请输入小包数量"
            style="width: 100%"
            @input="validateNumberInput"
            @blur="savePackNumber"
          ></el-input>
        </el-form-item>

        <el-form-item label="条码输入" prop="tempCode">
          <div class="code-input-box">
            <el-input
              v-model="tempCode"
              placeholder="请输入或扫描小包条码"
              @keyup.enter.native="handleCodeAction"
              class="code-input"
              @input="validateCodeInput"
            ></el-input>
            <el-button type="primary" @click="handleCodeAction">
              {{ packMode === 'normal' ? '添加' : '查询' }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="品种名称" prop="seed_id">
          <el-select v-model="packForm.seed_id" filterable placeholder="请选择品种" style="width: 100%" @change="saveSelectedSeed">
            <el-option v-for="item in seedList" :key="item.id" :label="item.name" :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">ID: {{ item.id }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="大包条码" prop="pack_code">
          <el-input
            v-model="packForm.pack_code"
            placeholder="请输入或扫描大包条码"
            @input="validateBigPackCodeInput"
            @blur="validateBigPackCodeOnBlur"
            style="width: 100%"
          ></el-input>
        </el-form-item>

        <el-form-item label="小包条码" prop="code">
          <div class="code-header">
            <span class="code-count">共 {{ packForm.code.length }} 个小包条码</span>
            <div class="code-actions">
              <el-button type="primary" @click="submitForm">绑定</el-button>
<!--              <el-button @click="resetForm">重置</el-button>-->
            </div>
          </div>
          <div class="code-box">
            <div v-for="(code, index) in packForm.code" :key="index" class="code-line">
              <span class="code-text">{{ code }}</span>
              <i class="el-icon-close code-delete" @click="handleRemoveCode(index)"></i>
            </div>
            <div v-if="packForm.code.length === 0" class="no-code-tip">暂无小包条码，请在上方输入并添加</div>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addPack } from '@/api/pack';
import { getSeedList, getOtherCode } from '@/api/seed';
import { AudioUtils } from '@/utils/audioUtils';

export default {
  name: 'PackIndex',
  data() {
    // 验证小包数量与条码数量是否一致（仅普通模式）
    const validateCodeCount = (rule, value, callback) => {
      if (this.packMode === 'normal' && this.packForm.code.length !== Number(this.packForm.number)) {
        callback(new Error(`小包条码数量需要等于小包数量(${this.packForm.number})`));
      } else {
        callback();
      }
    };

    return {
      packMode: 'normal', // 打包模式：normal-普通打包，piece-按件打包
      packForm: {
        number: '',
        code: [],
        pack_code: '',
        seed_id: '',
        small_pack_count: 0, // 小包数量
      },
      tempCode: '', // 临时存储输入的条码
      seedList: [],
      rules: {
        number: [
          { required: true, message: '请输入小包数量', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '只能输入正整数', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (Number(value) > 1000) {
                callback(new Error('小包数量不能超过1000'));
              } else {
                callback();
              }
            },
            trigger: 'blur',
          },
        ],
        seed_id: [{ required: true, message: '请选择品种名称', trigger: 'change' }],
        pack_code: [
          { required: true, message: '请输入大包条码', trigger: 'blur' },
          { pattern: /\d{19}$/, message: '大包条码格式不正确', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请添加小包条码', trigger: 'change' },
          { validator: validateCodeCount, trigger: 'change' },
        ],
      },
    };
  },

  mounted() {
    this.getSeedList();
    this.loadLastPackNumber();
  },

  watch: {
    // 监听小包数量变化，自动保存
    'packForm.small_pack_count': {
      handler(newVal) {
        if (newVal !== undefined && newVal !== null) {
          this.saveSmallPackCount(newVal);
        }
      },
      immediate: false
    }
  },

  methods: {
    // 播放成功提示音
    playSuccessSound() {
      try {
        AudioUtils.generateDingSound();
      } catch (error) {
        console.warn('播放成功提示音失败:', error);
      }
    },

    // 播放错误提示音
    playErrorSound() {
      try {
        AudioUtils.generateErrorSound();
      } catch (error) {
        console.warn('播放错误提示音失败:', error);
      }
    },

    // 语音播报
    playVoice(text) {
      try {

        if ('speechSynthesis' in window) {
          // 停止当前播报
          speechSynthesis.cancel();

          const utterance = new SpeechSynthesisUtterance(text);
          utterance.lang = 'zh-CN';
          utterance.rate = 1.0;
          utterance.pitch = 1.0;
          utterance.volume = 10.0;

          speechSynthesis.speak(utterance);
        }
      } catch (error) {
        console.warn('语音播报失败:', error);
      }
    },

    // 获取种子列表
    getSeedList() {
      getSeedList({
        page: 1,
        limit: 200, // 获取较多数据以便选择
      })
        .then((res) => {
          if (res.status === 200) {
            this.seedList = res.data.list || [];
            // 获取种子列表后，加载上次选择的品种
            this.loadLastSelectedSeed();
          } else {
            this.$message.error(res.msg || '获取种子列表失败');
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || '获取种子列表失败');
        });
    },

    // 保存选择的品种到localStorage
    saveSelectedSeed(seedId) {
      if (seedId) {
        // 找到选中的品种信息
        const selectedSeed = this.seedList.find(seed => seed.id == seedId);
        if (selectedSeed) {
          // 保存品种的完整信息，包括小包数量
          localStorage.setItem('lastSelectedSeed', JSON.stringify({
            id: selectedSeed.id,
            name: selectedSeed.name,
            small_pack_count: this.packForm.small_pack_count || 0
          }));
        }
      }
    },

    // 保存小包数量到localStorage
    saveSmallPackCount(count) {
      if (count !== undefined && count !== null) {
        localStorage.setItem('lastSmallPackCount', count.toString());
        // 同时更新品种选择记录中的小包数量
        const lastSelectedSeedStr = localStorage.getItem('lastSelectedSeed');
        if (lastSelectedSeedStr) {
          try {
            const lastSelectedSeed = JSON.parse(lastSelectedSeedStr);
            lastSelectedSeed.small_pack_count = count;
            localStorage.setItem('lastSelectedSeed', JSON.stringify(lastSelectedSeed));
          } catch (error) {
            console.warn('更新品种选择记录中的小包数量失败:', error);
          }
        }
      }
    },

    // 加载上次选择的品种
    loadLastSelectedSeed() {
      try {
        const lastSelectedSeedStr = localStorage.getItem('lastSelectedSeed');
        if (lastSelectedSeedStr && this.seedList.length > 0) {
          const lastSelectedSeed = JSON.parse(lastSelectedSeedStr);
          // 检查上次选择的品种是否还存在于种子列表中
          const seedExists = this.seedList.some(seed => seed.id == lastSelectedSeed.id);
          if (seedExists) {
            this.packForm.seed_id = lastSelectedSeed.id;
            // 加载上次选择的小包数量
            if (lastSelectedSeed.small_pack_count) {
              this.packForm.small_pack_count = lastSelectedSeed.small_pack_count;
            }
          } else {
            // 品种不存在，但尝试加载小包数量
            this.loadLastSmallPackCount();
          }
        } else {
          // 没有品种记录，尝试加载小包数量
          this.loadLastSmallPackCount();
        }
      } catch (error) {
        console.warn('加载上次选择的品种失败:', error);
        // 如果解析失败，尝试加载旧格式的数据
        const lastSelectedSeedId = localStorage.getItem('lastSelectedSeedId');
        if (lastSelectedSeedId && this.seedList.length > 0) {
          const seedExists = this.seedList.some(seed => seed.id == lastSelectedSeedId);
          if (seedExists) {
            this.packForm.seed_id = lastSelectedSeedId;
          }
        }
        // 尝试加载上次的小包数量
        this.loadLastSmallPackCount();
      }
    },

    // 加载上次的小包数量
    loadLastSmallPackCount() {
      const lastSmallPackCount = localStorage.getItem('lastSmallPackCount');
      if (lastSmallPackCount) {
        this.packForm.small_pack_count = parseInt(lastSmallPackCount) || 0;
      }
    },

    // 保存小包数量
    savePackNumber() {
      if (this.packForm.number && this.packMode === 'normal') {
        localStorage.setItem('lastPackNumber', this.packForm.number);
      }
    },

    // 加载上次输入的小包数量
    loadLastPackNumber() {
      if (this.packMode === 'normal') {
        const lastPackNumber = localStorage.getItem('lastPackNumber');
        if (lastPackNumber) {
          this.packForm.number = lastPackNumber;
        }
      }
    },

    // 添加小包条码
    handleAddCode() {
      if (!this.tempCode) {
        const errorMsg = '请输入条码';
        this.$message.warning(errorMsg);
        this.playErrorSound();
        setTimeout(() => {
          this.playVoice(errorMsg);
        }, 400);
        return;
      }

      // 验证小包条码格式
      const smallCodeRegex = /\d{20}$/;
      if (!smallCodeRegex.test(this.tempCode)) {
        const errorMsg = '小包条码格式不正确';
        this.$message.warning(errorMsg);
        this.playErrorSound();
        setTimeout(() => {
          this.playVoice(errorMsg);
        }, 400);
        return;
      }

      // 检查是否已存在相同条码
      if (this.packForm.code.includes(this.tempCode)) {
        const errorMsg = '该条码已添加';
        this.$message.warning(errorMsg);
        // 播放错误提示音和语音
        this.playErrorSound();
        setTimeout(() => {
          this.playVoice(errorMsg);
        }, 400);
        this.tempCode = '';
        return;
      }

      // 检查是否超过设定的小包数量
      if (this.packForm.code.length >= Number(this.packForm.number)) {
        const errorMsg = `小包条码数量已达到${this.packForm.number}个上限`;
        this.$message.warning(errorMsg);
        this.playErrorSound();
        setTimeout(() => {
          this.playVoice(errorMsg);
        }, 400);
        this.tempCode = '';
        return;
      }

      // 添加条码
      this.packForm.code.push(this.tempCode);
      this.tempCode = '';

      // 播放成功提示音
      this.playSuccessSound();

      // 根据剩余数量播放语音提示
      const currentCount = this.packForm.code.length;
      const totalCount = Number(this.packForm.number);
      const remaining = totalCount - currentCount;

      // 延迟播放语音，确保提示音播放完成后再播放语音
      setTimeout(() => {
        if (remaining === 0) {
          // 最后一袋录入后
          this.playVoice('请扫大码');
          // 自动将焦点移动到大包条码输入框
          this.$nextTick(() => {
            const packCodeInput = document.querySelector('input[placeholder="请输入或扫描大包条码"]');
            if (packCodeInput) {
              packCodeInput.focus();
            }
          });
        } else if (remaining === 1) {
          // 倒数第2袋录入后
          this.playVoice('差1');
        } else if (remaining === 2) {
          // 倒数第3袋录入后
          this.playVoice('差2');
        } else if (remaining === 3) {
          // 倒数第4袋录入后
          this.playVoice('差3');
        }
      }, 400); // 延迟400ms，确保提示音播放完成

      // 触发验证
      this.$refs.packForm.validateField('code');
    },

    // 移除小包条码
    handleRemoveCode(index) {
      this.packForm.code.splice(index, 1);

      // 触发验证
      this.$refs.packForm.validateField('code');
    },
    // 验证数字输入
    validateNumberInput(value) {
      // 只允许输入数字
      this.packForm.number = value.replace(/\D/g, '');
      // 不允许输入0开头的数字
      if (this.packForm.number.startsWith('0')) {
        this.packForm.number = this.packForm.number.replace(/^0+/, '');
      }
      // 如果为空或0,设置为1
      // if (!this.packForm.number || this.packForm.number === '0') {
      // this.packForm.number = '';
      // return;
      // }
      // 限制最大值为1000
      if (Number(this.packForm.number) > 1000) {
        this.packForm.number = '1000';
      }
    },

    // 验证小包条码输入，只允许输入20位数字
    validateCodeInput(value) {
      // 移除非数字字符
      let numStr = value.replace(/\D/g, '');
      // 限制最大长度为20位
      if (numStr.length > 20) {
        numStr = numStr.slice(0, 20);
      }
      this.tempCode = numStr;

      // 当输入达到20位数字时，自动触发相应操作
      if (numStr.length === 20) {
        // 延迟执行，确保输入框值已更新
        this.$nextTick(() => {
          this.handleCodeAction();
        });
      }
    },

    // 验证大包条码输入，只允许输入数字
    validateBigPackCodeInput(value) {
      // 移除非数字字符
      let numStr = value.replace(/\D/g, '');
      
      // 如果输入超过19位，截取前19位并给出提示
      if (numStr.length > 19) {
        numStr = numStr.slice(0, 19);
        const errorMsg = '大包条码只能输入19位数字';
        this.$message.warning(errorMsg);
        this.playErrorSound();
        setTimeout(() => {
          this.playVoice(errorMsg);
        }, 400);
      }
      
      this.packForm.pack_code = numStr;
    },

    // 大包条码失去焦点时验证
    validateBigPackCodeOnBlur() {
      const code = this.packForm.pack_code;
      if (code && code.length !== 19) {
        const errorMsg = '大包条码必须是19位数字';
        this.$message.warning(errorMsg);
        this.playErrorSound();
        setTimeout(() => {
          this.playVoice(errorMsg);
        }, 400);
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.packForm.validate((valid) => {
        if (valid) {
          // 普通模式需要验证小包条码数量是否与设定数量一致
          if (this.packMode === 'normal' && this.packForm.code.length !== Number(this.packForm.number)) {
            const errorMsg = `小包条码数量(${this.packForm.code.length})与设定的小包数量(${this.packForm.number})不一致`;
            this.$message.error(errorMsg);
            this.playErrorSound();
            setTimeout(() => {
              this.playVoice(errorMsg);
            }, 400);
            return;
          }

          // 按件模式需要确保有小包条码
          if (this.packMode === 'piece' && this.packForm.code.length === 0) {
            const errorMsg = '请先查询小包条码';
            this.$message.error(errorMsg);
            this.playErrorSound();
            setTimeout(() => {
              this.playVoice(errorMsg);
            }, 400);
            return;
          }

          // 按件模式需要设置小包数量为实际条码数量
          if (this.packMode === 'piece') {
            this.packForm.number = this.packForm.code.length;
          }

          addPack(this.packForm)
            .then((res) => {
              if (res.status === 200) {
                this.$message.success('打包成功');
                // 播放成功提示音和语音
                this.playSuccessSound();
                setTimeout(() => {
                  this.playVoice('打包成功');
                }, 400);

                this.resetForm();

                
                // 重置表单后，将焦点移回条码输入框
                this.$nextTick(() => {
                  const codeInput = document.querySelector('input[placeholder="请输入或扫描小包条码"]');
                  if (codeInput) {
                    codeInput.focus();
                  }
                });

                this.loadLastSelectedSeed();
                this.loadLastPackNumber();
              } else {
                const errorMsg = res.msg || '打包失败';
                this.$message.error(errorMsg);
                // 播放错误提示音
                this.playErrorSound();
                setTimeout(() => {
                  this.playVoice(errorMsg);
                }, 400);
              }
            })
            .catch((err) => {
              if (err.status === 400 && err.data) {
                // 处理部分小包条码已被使用的情况
                const usedCodes = err.data || [];
                const originalCount = this.packForm.code.length;

                // 移除已使用的条码
                this.packForm.code = this.packForm.code.filter((code) => !usedCodes.includes(code));

                // 更新小包数量（普通模式需要手动调整）
                if (this.packMode === 'normal') {
                  this.packForm.number = this.packForm.code.length;
                }

                // 显示处理结果
                const warningMsg = `已移除${usedCodes.length}个已使用的条码，剩余${this.packForm.code.length}个可用条码`;
                this.$message.warning(warningMsg);
                this.playErrorSound();
                
                // 如果还有剩余条码，提示用户可以重新提交
                let infoMsg = '';
                if (this.packForm.code.length > 0) {
                  infoMsg = '请检查剩余条码后重新提交';
                  this.$message.info(infoMsg);
                } else {
                  infoMsg = '所有条码都已被使用，请重新添加条码';
                  this.$message.error(infoMsg);
                }
                
                // 语音播报完整信息
                setTimeout(() => {
                  this.playVoice(warningMsg + '，' + infoMsg);
                }, 400);

                // 触发验证更新
                this.$refs.packForm.validateField('code');
              } else {
                const errorMsg = err.msg || '打包失败';
                this.$message.error(errorMsg);
                this.playErrorSound();
                setTimeout(() => {
                  this.playVoice(errorMsg);
                }, 400);
              }
            });
        }
      });
    },

    // 重置表单
    resetForm() {
      this.$refs.packForm.resetFields();
      this.packForm = {
        number: this.packMode === 'piece' ? 0 : '',
        code: [],
        pack_code: '',
        seed_id: '',
        small_pack_count: 0, // 重置小包数量
      };
      this.tempCode = '';
    },
    // 切换打包模式
    switchMode(mode) {
      this.packMode = mode;
      // 切换模式时重置表单
      this.resetForm();
      // 重新加载对应模式的数据
      // if (mode === 'normal') {
        this.loadLastPackNumber();
      // }
      this.loadLastSelectedSeed();
    },
    // 条码操作（添加或查询）
    handleCodeAction() {
      if (this.packMode === 'normal') {
        this.handleAddCode();
      } else {
        this.handleQueryOtherCodes();
      }
    },

    // 按件打包：查询其他小码
    handleQueryOtherCodes() {
      if (!this.tempCode) {
        const errorMsg = '请输入条码';
        this.$message.warning(errorMsg);
        this.playErrorSound();
        setTimeout(() => {
          this.playVoice(errorMsg);
        }, 400);
        return;
      }

      // 验证小包条码格式
      const smallCodeRegex = /\d{20}$/;
      if (!smallCodeRegex.test(this.tempCode)) {
        const errorMsg = '小包条码格式不正确';
        this.$message.warning(errorMsg);
        this.playErrorSound();
        setTimeout(() => {
          this.playVoice(errorMsg);
        }, 400);
        return;
      }

      // 调用API查询其他小码
      getOtherCode(this.tempCode)
        .then((res) => {
          if (res.status === 200) {
            const codeList = res.data || [];
            if (codeList.length === 0) {
              const errorMsg = '未查询到相关小码';
              this.$message.warning(errorMsg);
              this.playErrorSound();
              setTimeout(() => {
                this.playVoice(errorMsg);
              }, 400);
              return;
            }

            // 清空现有条码，添加查询到的条码
            this.packForm.code = [...codeList];
            this.tempCode = '';

            this.$message.success(`查询成功，共获取到${codeList.length}个小码`);

            // 播放成功提示音和语音
            this.playSuccessSound();
            setTimeout(() => {
              this.playVoice(`查询成功，共${codeList.length}个小码`);
              
              // 自动将焦点移动到大包条码输入框
              this.$nextTick(() => {
                const packCodeInput = document.querySelector('input[placeholder="请输入或扫描大包条码"]');
                if (packCodeInput) {
                  packCodeInput.focus();
                }
              });
            }, 400);

            // 触发验证
            this.$refs.packForm.validateField('code');
          } else {
            const errorMsg = res.msg || '查询失败';
            this.$message.error(errorMsg);
            this.playErrorSound();
            setTimeout(() => {
              this.playVoice(errorMsg);
            }, 400);
          }
        })
        .catch((err) => {
          const errorMsg = err.msg || '查询失败';
          this.$message.error(errorMsg);
          this.playErrorSound();
          setTimeout(() => {
            this.playVoice(errorMsg);
          }, 400);
        });
    },
  },
};
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mode-switch {
  .el-button-group {
    .el-button {
      padding: 8px 16px;
      font-size: 14px;
    }
  }
}

.pack-form {
  max-width: 600px;
  margin: 0 auto;
}

.code-input-box {
  display: flex;
  align-items: center;
  width: 100%;

  .code-input {
    margin-right: 10px;
    flex: 1;
  }
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.code-count {
  font-size: 14px;
  color: #606266;
}

.code-actions {
  .el-button {
    margin-left: 10px;
  }
}

.code-box {
  height: 300px;
  overflow-y: auto;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 4px;
  background-color: #f9f9f9;
  width: 100%;

  .code-line {
    display: flex;
    // margin-bottom: 4px;
    align-items: center;
  }

  .code-text {
    font-size: 14px;
    margin-right: 5px;
  }

  .code-delete {
    cursor: pointer;
    color: #f56c6c;
    &:hover {
      color: #ff4949;
    }
  }

  .no-code-tip {
    color: #909399;
    text-align: center;
    padding: 20px 0;
  }
}
</style>
